CPP核心准则:通用和局部名称简短,特殊和非局部名称较长

ES.7: Keep common and local names short, and keep uncommon and non-local names longer

ES.7: 通用和局部的名称应该简短,特殊和非局部的名称应该较长。

Reason(原因)

Readability. Lowering the chance of clashes between unrelated non-local names.

可读性。避免无关的非局部名称之间的冲突。

Example(示例)

Conventional short, local names increase readability:

遵循惯例的,简短的局部变量可以增加可读性。

template<typename T>    // good
void print(ostream& os, const vector<T>& v)
{
    for (gsl::index i = 0; i < v.size(); ++i)
        os << v[i] << '\n';
}

An index is conventionally called i and there is no hint about the meaning of the vector in this generic function, so v is as good name as any. Compare

索引习惯上命名为i;在这个通用函数中,关于vector的含义没有任何参考信息,因此v也是一个好名字。

template<typename Element_type>   // bad: verbose, hard to read
void print(ostream& target_stream, const vector<Element_type>& current_vector)
{
    for (gsl::index current_element_index = 0;
         current_element_index < current_vector.size();
         ++current_element_index
    )
    target_stream << current_vector[current_element_index] << '\n';
}

Yes, it is a caricature, but we have seen worse.

是的,这段代码有点夸张,但是我们确实看过更差的。

Example(示例)

Unconventional and short non-local names obscure code:

特殊且很短的非局部名称会扰乱代码:

void use1(const string& s)
{
    // ...
    tt(s);   // bad: what is tt()?
    // ...
}

Better, give non-local entities readable names:

稍好一点的做法是,为非局部实体提供可读的名称:

void use1(const string& s)
{
    // ...
    trim_tail(s);   // better
    // ...
}

Here, there is a chance that the reader knows what trim_tail means and that the reader can remember it after looking it up.

存在这样的可能性:读者能够理解trim_tail的含义并且可以在查阅代码之后能够记住它。

Example, bad(反面示例)

Argument names of large functions are de facto non-local and should be meaningful:

长函数的参数名属于事实上的非局部变量,应该具有明确的含义:

void complicated_algorithm(vector<Record>& vr, const vector<int>& vi, map<string, int>& out)
// read from events in vr (marking used Records) for the indices in
// vi placing (name, index) pairs into out
{
    // ... 500 lines of code using vr, vi, and out ...
}

We recommend keeping functions short, but that rule isn't universally adhered to and naming should reflect that.

我们推荐保持函数简短,但是该规则不会适用于所有情况,名称也应该反映这种变化。

Enforcement(实施建议)

Check length of local and non-local names. Also take function length into account.

检查局部和非局部变量的长度。注意同时考虑函数的长度。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es7-keep-common-and-local-names-short-and-keep-uncommon-and-non-local-names-longer

本页共74段,2793个字符,3577 Byte(字节)